import 'dart:async';
import 'dart:convert';

import 'package:data_table_2/data_table_2.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:yuellyfactory/util/BaseRequest.dart';
import 'package:yuellyfactory/util/MathUtil.dart';
import 'package:yuellyfactory/views/model/TypeConfigVC.dart';

import '../../eventbus/EventBusUtil.dart';
import '../../eventbus/EventRefreshMaterial.dart';
import '../../util/ColorUtil.dart';
import '../../util/GlobalData.dart';
import '../../util/ToastUtil.dart';
import '../../util/ViewUtil.dart';
import '../../util/XNumberTextInputFormatter.dart';
import '../dto/Parameters.dart';
import '../dto/PricePart.dart';
import 'ModelConfigVC.dart';

class EditMaterialView extends StatefulWidget {
  const EditMaterialView({super.key});

  @override
  State<EditMaterialView> createState() => _EditMaterialViewState();
}

class _EditMaterialViewState extends State<EditMaterialView> {

  // 固定高度参数（可根据需求调整）
  final double _headerHeight = 56; // 表头高度（含内边距）
  final double _rowHeight = 48; // 每行高度（含内边距）
  final double _borderWidth = 1; // 边框宽度
  final double _outerPadding = 10; // 表格外间距
  StreamSubscription? streamSubscription;

  final dialogKey = GlobalKey<ShadFormState>();
  PricePart pricePart=PricePart();
  List<PricePart> configData=[];

  Map<String,bool> showMaps={};

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    streamSubscription = eventBus.on<EvetnRefreshMaterial>().listen((event) {
      pricePart=event.pricePart;
      getData();
    });
  }

  @override
  void dispose() {
    if (streamSubscription != null) {
      streamSubscription!.cancel();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // 获取屏幕尺寸用于约束
    final screenSize = MediaQuery.of(context).size;

    return SingleChildScrollView(
      // 关键：添加physics避免滚动冲突
      physics: const ClampingScrollPhysics(),
      child: Column(
        // 关键：设置mainAxisSize为min，避免Column试图无限扩展
        mainAxisSize: MainAxisSize.min,
        children: getViews(),
      ),
    );
  }

  List<Widget> getViews(){
    List<Widget> views=[];

    views.add(Row(
      children: [
        Text('${getCrumbName()}',style: TextStyle(fontSize: ViewUtil.fontSize(22),fontWeight: FontWeight.bold),),
        SizedBox(width: ViewUtil.screenWidth(20),),
        Expanded(child: Container()),
        ViewUtil.configIcon('型号设置',(){
          showShadSheet(
            side: ShadSheetSide.right,
            context: context,
            builder: (context) => ModelConfigVC(callback: (){}, pricePart: pricePart)

            ,
          );
        })

      ],
    ));
    views.add(ViewUtil.lineView());

    for(PricePart pricePart in configData){
      views.add(materialView(pricePart));

    }

    return views;
  }

  getCrumbName(){
    List list= ViewUtil.crumbModelList(pricePart.id,GlobalData.modelData);
    var name="";
    for(var i=0;i<list.length;i++){
      PricePart part=list[i];
      name=name+part.name;
      if(i!=list.length-1){
        name="$name > ";
      }
    }
    return name;
  }


  Widget materialView(PricePart part) {




    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        // 标题和按钮
        Padding(
          padding: EdgeInsets.symmetric(horizontal: _outerPadding),
          child: Row(
            children: [
              Text(
                '分类：${part.name}',
                style: TextStyle(fontSize: ViewUtil.fontSize(28)),
              ),
              Expanded(child: Container()),
              IconButton(icon:  Icon( getIsShow(part.id)?Icons.keyboard_arrow_down_outlined:Icons.keyboard_arrow_right_outlined),
                color:ColorUtil.colorBlue,
                iconSize: ViewUtil.screenWidth(35),onPressed: (){
                  bool result= getIsShow(part.id);
                  result=!result;
                  showMaps[part.id]=result;
                  setState(() {

                  });
                },),
              // ViewUtil.addIcon('添加品牌',(){
              //   getAllBrand(part);
              // }),
              // ViewUtil.delIcon('删除配置',(){
              //   showDelDialog(part);
              // })
              ViewUtil.configIcon("可选配置", (){
                showShadSheet(
                  side: ShadSheetSide.right,
                  context: context,
                  builder: (context) => TypeConfigVC(callback: (){}, pricePart: pricePart,typePart: part,)

                  ,
                );
              }),

            ],
          ),
        ),
        ViewUtil.lineView(),
        //品牌
        Visibility(visible: getIsShow(part.id),
            child: brandWidgets(part)),

        const SizedBox(height: 10),
      ],
    );
  }




  Widget brandWidgets(PricePart partData){
    List<Widget> widges=[];
    for(PricePart partItem in partData.materialList){
      widges.add(
          Container(
            margin: EdgeInsets.only(left: _outerPadding*2,right: _outerPadding),
            child: Column(
              children: [
                Row(
                  children: [
                    Text('品牌 : ${partItem.name}',style: TextStyle(fontSize: ViewUtil.fontSize(28),fontWeight: FontWeight.bold),),
                    SizedBox(width: ViewUtil.screenWidth(20),),
                    Expanded(child: Container()),
                    IconButton(icon:  Icon( getIsShow(partItem.id)?Icons.keyboard_arrow_down_outlined:Icons.keyboard_arrow_right_outlined),
                      color:ColorUtil.colorBlue,
                      iconSize: ViewUtil.screenWidth(35),onPressed: (){
                        bool result= getIsShow(partItem.id);
                        result=!result;
                        showMaps[partItem.id]=result;
                        setState(() {

                        });
                      },),
                    // ViewUtil.addIcon('添加系列',(){
                    //   //添加系列
                    //   getSerialList(partItem);
                    // }),
                    // ViewUtil.delIcon('删除配置',(){
                    //   showDelDialog(partItem);
                    // })
                  ],
                ),
                ViewUtil.lineView(),
                Visibility(
                    visible: getIsShow(partItem.id),
                    child: serialViews(partItem))
              ],
            ),
          )

      );
    }
    return Column(
      children: widges,
    );
  }
  
  Widget serialViews(PricePart partData){
    List<Widget> widges=[];
    for(PricePart partItem in partData.materialList){
      widges.add(
          Container(
            margin: EdgeInsets.only(left: _outerPadding),
            child: Column(
              children: [
                Row(
                  children: [
                    Text('系列 : ${partItem.name}',style: TextStyle(fontSize: ViewUtil.fontSize(28),fontWeight: FontWeight.bold),),
                    SizedBox(width: ViewUtil.screenWidth(20),),
                    Expanded(child: Container()),
                    IconButton(icon:  Icon( getIsShow(partItem.id)?Icons.keyboard_arrow_down_outlined:Icons.keyboard_arrow_right_outlined),
                      color:ColorUtil.colorBlue,
                      iconSize: ViewUtil.screenWidth(35),onPressed: (){
                        bool result= getIsShow(partItem.id);
                        result=!result;
                        showMaps[partItem.id]=result;
                        setState(() {

                        });
                      },),
                    // ViewUtil.addIcon('添加型号',(){
                    //   //添加材料
                    //   getAllMaterial(partItem);
                    // }),
                    // ViewUtil.delIcon('删除配置',(){
                    //   showDelDialog(partItem);
                    // })
                  ],
                ),


               // 表格（高度固定为计算值）
                Visibility(
                  visible: getIsShow(partItem.id),
                  child:materialTableView(partItem)
                 ),

              ],
            ),
          )

      );
    }
    return Column(
      children: widges,
    );
  }

  Widget materialTableView(PricePart partData){
    // 计算表格总高度
    final double tableHeight = _calculateTableHeight(partData);
    return  Container(
      // 应用计算出的高度
      height: tableHeight,
      margin: EdgeInsets.only(right: 10),
      decoration: BoxDecoration(
        border: Border.all(color: Colors.grey[200]!, width: _borderWidth),
        borderRadius: BorderRadius.circular(8),
      ),
      child: DataTable2(
        columnSpacing: 12,
        //  minWidth: MediaQuery.of(context).size.width - 2 * _outerPadding,
        minWidth: 1500,
        headingRowHeight: _headerHeight - 2 * _borderWidth, // 减去边框占用高度
        dataRowHeight: _rowHeight - 2 * _borderWidth, // 减去边框占用高度
        // 表头
        columns: const [
          DataColumn2(
            label: Text('  操作'),
            fixedWidth: 60,
          ),
          DataColumn2(
            label: Text('型号名称'),
            fixedWidth: 150,
          ),
          DataColumn2(
            label: Text('数量'),
            fixedWidth: 60,
          ),

          DataColumn2(
            label: Text('物料编码'),
            fixedWidth: 100,
          ),
          DataColumn2(
            label: Text('型号说明'),
            fixedWidth: 600,
          ),

        ],

        // 表格内容（行高固定）
        rows: partData.materialList.map((item) {
          return DataRow(cells: [
            DataCell(
              ViewUtil.delIcon('删除型号',(){
                showDelDialog(item);
              })
            ),
            DataCell(Padding(
              padding: const EdgeInsets.symmetric(vertical: 12),
              child: Text(item.name),
            )),
            DataCell(Padding(
              padding: const EdgeInsets.symmetric(vertical: 12),
              child: Text(MathUtil.formatDouble(item.count, 2)),
            )),
            DataCell(Padding(
              padding: const EdgeInsets.symmetric(vertical: 12),
              child: Text(item.code),
            )),
            DataCell(
                GestureDetector(onTap: (){
                  List<Parameters> datas=[];
                  datas.add(Parameters("型号名称", item.name));
                  datas.add(Parameters("Code", item.code));
                  var spec=item.spec;
                  if(spec.isNotEmpty){
                    var  specsList=jsonDecode(spec);
                    for(var item in specsList){
                      datas.add(Parameters(item["name"],item["value"]));
                    }
                  }
                  ViewUtil.showParmSheet(context, '规格参数', datas);
                },child: Padding(
                  padding: const EdgeInsets.symmetric(vertical: 12),
                  child: Text(getPartSpec(item)),
                ),)
            ),

          ]);
        }).toList(),
      ),
    );
  }


  // 计算表格总高度的核心方法
  double _calculateTableHeight(PricePart part) {
    // 总高度 = 表头高度 + 数据行总高度 + 边框总高度
    // 边框高度：上下边框（2条）+ 行之间的分隔线（数据行数-1条）
    final int borderCount = 2 + (part.materialList.length - 1);
    final double totalBorderHeight = borderCount * _borderWidth;

    return _headerHeight + // 表头高度
        (_rowHeight * part.materialList.length) + // 所有数据行高度
        totalBorderHeight; // 边框总高度
  }


  void showDelDialog(PricePart material){
    showShadDialog(
      context: context,
      builder: (context) => ShadDialog.alert(
        title: Text('确定要删除${material.name}吗?'),
        description: const Padding(
          padding: EdgeInsets.only(bottom: 8),
          child: Text(
            '点击删除将取消配置',
          ),
        ),
        actions: [
          ShadButton.outline(
            child: const Text('取消'),
            onPressed: () => Navigator.of(context).pop(false),
          ),
          ShadButton(
            child: const Text('删除'),
            onPressed: () {
              requestDelMaterial(material);
            },
          ),
        ],
      ),
    );
  }

  void requestDelMaterial(PricePart material){
    var parm={
      "id":material.configId
    };
    BaseRequest.postHttp('price/delconfigpart',parameters: parm, canTip: true, context: context, onSuccess: (data){
      bool result = BaseRequest.chekResponse(data, true);
      if (result) {
        ToastUtil.showToast("删除成功");
        getData();
        Navigator.pop(context);
      }
    }, onError: (error){});
  }

  void getAllMaterial(PricePart partData){
    var parm={
      "id":partData.id
    };
    BaseRequest.postHttp('price/baseallserialmaterial',parameters: parm, canTip: true , context: context, onSuccess: (data){
      bool result = BaseRequest.chekResponse(data, true);
      if (result) {
        dynamic datas = data["data"];
        var items={};
        for (var i = 0; i < datas.length; i++) {
          var item = datas[i];
          var id=item["id"];
          var name=item["name"];
          items[id]=name;
        }
        addMatterialDialog(items,partData);
      }
    }, onError: (error){

    });
  }

  void addMatterialDialog(var options,PricePart part) {
    //选择零件列表。
    showShadDialog(context: context, builder: (context) =>
        ShadDialog(
            actions: [ShadButton(child: Text('确定'), onPressed: () {
              submitAddMaterial(part);
            },)
            ],
            child:
            ShadForm(
              key: dialogKey,
              child:
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      ShadSelectFormField<String>(
                        id: 'material',
                        label: const Text('材料'),
                        minWidth: 350,
                        options: (options as Map).entries
                            .map((e) => ShadOption(value: e.key.toString(), child: Text(e.value.toString())))
                            .toList(), // 注意添加toList()转换
                        selectedOptionBuilder: (context, value) {
                          if (value == null || value == 'none') {
                            return const Text('请选择材料');
                          }
                          // 使用空值合并运算符??代替!，提供默认值
                          return Text((options as Map)[value]?.toString() ?? '未知选项');
                        },
                        placeholder: const Text('请选择材料'),
                        validator: (v) {
                          if (v == null) {
                            return '请选择材料';
                          }
                          return null;
                        },
                      ),
                      const SizedBox(height: 10),
                      ShadInputFormField(
                        id: 'count',
                        initialValue: "1",
                        keyboardType: TextInputType.numberWithOptions(decimal: true),
                        inputFormatters: [
                          FilteringTextInputFormatter.allow(RegExp("[0-9.]")),
                          XNumberTextInputFormatter(
                              maxIntegerLength: null,
                              maxDecimalLength: 2,
                              isAllowDecimal: true),
                        ],
                        label: const Text('数量'),
                        placeholder: const Text('请输入数量'),
                        validator: (v) {
                          if (v.isEmpty) {
                            return '请输入数量';
                          }
                          return null;
                        },
                      ),
                    ],
                  )

            )

        )
    );

  }

  void submitAddMaterial(PricePart partData){
    if (dialogKey.currentState!.saveAndValidate()) {
      var values = dialogKey.currentState!.value;
      var material = values["material"];
      var count=values["count"];
      var parm={
        "modelId":pricePart!.modelId,
        "partId":material,
        "parentId":partData.configId,
        "count":count,
        "type":"part"
      };
      BaseRequest.postHttp('price/addconfigpart',parameters: parm, canTip: true, context: context, onSuccess: (data){
        bool result = BaseRequest.chekResponse(data, true);
        if (result) {
          ToastUtil.showToast("添加成功");
          getData();
          Navigator.pop(context);
        }
      }, onError: (error){});
    }
  }

  void getAllBrand(PricePart partData){
    var parm={
      "id":partData.id
    };
    BaseRequest.postHttp('price/baseallbrand',parameters: parm, canTip: true , context: context, onSuccess: (data){
      bool result = BaseRequest.chekResponse(data, true);
      if (result) {
        dynamic datas = data["data"];
        var items={};
        for (var i = 0; i < datas.length; i++) {
          var item = datas[i];
          var id=item["id"];
          var name=item["name"];
          items[id]=name;
        }
        addBrandDialog(items,partData);

      }
    }, onError: (error){

    });
  }

  void addBrandDialog(var options,PricePart part) {
    //选择品牌列表。
    showShadDialog(context: context, builder: (context) =>
        ShadDialog(
            actions: [ShadButton(child: Text('确定'), onPressed: () {
              submitAddBrand(part);
            },)
            ],
            child:
            ShadForm(
                key: dialogKey,
                child:
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    ShadSelectFormField<String>(
                      id: 'brand',
                      label: const Text('品牌'),
                      minWidth: 350,
                      options: (options as Map).entries
                          .map((e) => ShadOption(value: e.key.toString(), child: Text(e.value.toString())))
                          .toList(), // 注意添加toList()转换
                      selectedOptionBuilder: (context, value) {
                        if (value == null || value == 'none') {
                          return const Text('请选择品牌');
                        }
                        // 使用空值合并运算符??代替!，提供默认值
                        return Text((options as Map)[value]?.toString() ?? '未知选项');
                      },
                      placeholder: const Text('请选择品牌'),
                      validator: (v) {
                        if (v == null) {
                          return '请选择品牌';
                        }
                        return null;
                      },
                    ),
                  ],
                )

            )

        )
    );

  }

  void submitAddBrand(PricePart partData){
    if (dialogKey.currentState!.saveAndValidate()) {
      var values = dialogKey.currentState!.value;
      var material = values["brand"];

      var parm={
        "modelId":pricePart!.modelId,
        "partId":material,
        "parentId":partData.configId,
        "type":"brand",
        "count":0,
      };
      BaseRequest.postHttp('price/addconfigpart',parameters: parm, canTip: true, context: context, onSuccess: (data){
        bool result = BaseRequest.chekResponse(data, true);
        if (result) {
          ToastUtil.showToast("添加成功");
          getData();
          Navigator.pop(context);
        }
      }, onError: (error){});
    }
  }

  void addSerialDialog(var options,PricePart part) {
    //选择品牌列表。
    showShadDialog(context: context, builder: (context) =>
        ShadDialog(
            actions: [ShadButton(child: Text('确定'), onPressed: () {
              submitAddSerial(part);
            },)
            ],
            child:
            ShadForm(
                key: dialogKey,
                child:
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    ShadSelectFormField<String>(
                      id: 'serial',
                      label: const Text('系列'),
                      minWidth: 350,
                      options: (options as Map).entries
                          .map((e) => ShadOption(value: e.key.toString(), child: Text(e.value.toString())))
                          .toList(), // 注意添加toList()转换
                      selectedOptionBuilder: (context, value) {
                        if (value == null || value == 'none') {
                          return const Text('请选择系列');
                        }
                        // 使用空值合并运算符??代替!，提供默认值
                        return Text((options as Map)[value]?.toString() ?? '未知选项');
                      },
                      placeholder: const Text('请选择系列'),
                      validator: (v) {
                        if (v == null) {
                          return '请选择系列';
                        }
                        return null;
                      },
                    ),
                  ],
                )

            )

        )
    );

  }

  void submitAddSerial(PricePart partData){
    if (dialogKey.currentState!.saveAndValidate()) {
      var values = dialogKey.currentState!.value;
      var material = values["serial"];

      var parm={
        "modelId":pricePart!.modelId,
        "partId":material,
        "parentId":partData.configId,
        "type":"serial",
        "count":0,
      };
      BaseRequest.postHttp('price/addconfigpart',parameters: parm, canTip: true, context: context, onSuccess: (data){
        bool result = BaseRequest.chekResponse(data, true);
        if (result) {
          ToastUtil.showToast("添加成功");
          getData();
          Navigator.pop(context);
        }
      }, onError: (error){});
    }
  }

  void getSerialList(PricePart partData){
    var parm={
      "id":partData.id
    };
    BaseRequest.postHttp('price/baseallserial',parameters: parm, canTip: true , context: context, onSuccess: (data){
      bool result = BaseRequest.chekResponse(data, true);
      if (result) {
        dynamic datas = data["data"];
        var items={};
        for (var i = 0; i < datas.length; i++) {
          var item = datas[i];
          var id=item["id"];
          var name=item["name"];
          items[id]=name;
        }
        addSerialDialog(items,partData);

      }
    }, onError: (error){

    });
  }

  void getData(){
    var parm={
      "modelId":pricePart!.id
    };
    BaseRequest.postHttp('price/getproductconfig',parameters: parm, canTip: true , context: context, onSuccess: (data){
      bool result = BaseRequest.chekResponse(data, true);
      if (result) {
        dynamic datas = data["data"];
        List<PricePart> allModel = [];
        for (var i = 0; i < datas.length; i++) {
          var item = datas[i];
          var part = PricePart.fromJson(item);
          allModel.add(part);
        }
        configData=allModel;
        setState(() {

        });

      }
    }, onError: (error){

    });
  }

  getIsShow(String id){
    bool result=false;
    if(showMaps.containsKey(id)){
      return showMaps[id];
    }
    return result;
  }



  getPartSpec(PricePart partData){
    var spec=partData.spec;
    var value="";
    if(spec.isNotEmpty){
      var  specsList=jsonDecode(spec);
      for(var item in specsList){
        var str="${item["name"]}:${item["value"]}";
        value="$value$str | ";
      }
    }

    return value;
  }
}
